<template>
	<view class="evaluate-container">
		<!-- 商品信息 -->
		<view class="product-info">
			<view class="product-detail">
				<text class="product-name">{{ dishNames }}</text>
				<text class="product-price">合计：¥{{ orderDetail.totalAmount }}</text>
			</view>
		</view>
		<!-- 评分区域 -->
		<view class="rating-section">
			<view class="section-title">整体评价</view>
			<star-rating v-model="rating" :showText="true"></star-rating>
			<!-- 
			<view class="section-title" style="margin-top: 40rpx;">描述相符</view>
			<star-rating v-model="descriptionRating"></star-rating> -->
		</view>
		<!-- 评价输入 -->
		<view class="evaluate-input">
			<textarea v-model="content" placeholder="宝贝满足你的期待吗？说说你的用餐心得，分享给想买的他们吧~" maxlength="500"
				class="textarea"></textarea>
			<view class="word-count">{{ content.length }}/500</view>
		</view>
		<!-- 上传图片 -->
		<view class="upload-section">
			<view class="section-title">上传图片</view>
			<view class="upload-list">
				<view v-for="(image, index) in imageList" :key="index" class="upload-item">
					<image :src="image" mode="aspectFill" class="uploaded-image"></image>
					<uni-icons type="clear" size="16" color="#fff" class="delete-icon"
						@click="deleteImage(index)"></uni-icons>
				</view>
				<view v-if="imageList.length < 5" class="upload-btn" @click="chooseImage">
					<uni-icons type="plusempty" size="30" color="#999"></uni-icons>
					<text class="upload-text">添加图片</text>
				</view>
			</view>
			<view class="upload-tip">最多可上传5张图片</view>
		</view>
		<!-- 匿名评价 -->
	<!-- 	<view class="anonymous-section">
			<checkbox-group @change="anonymousChange">
				<label class="anonymous-label">
					<checkbox value="1" :checked="isAnonymous" class="anonymous-checkbox" />
					<text class="anonymous-text">匿名评价</text>
				</label>
			</checkbox-group>
		</view> -->

		<view class="custom-checkbox" @click="isAnonymous = !isAnonymous">
			<view class="checkbox-box" :class="{checked: isAnonymous}">
				<uni-icons v-if="isAnonymous" type="checkmarkempty" size="16" color="#fff"></uni-icons>
			</view>
			<text>匿名评价</text>
		</view>
		<!-- 提交按钮 -->
		<button type="primary" class="submit-btn" :disabled="!canSubmit" @click="submitEvaluate">
			提交评价
		</button>
	</view>
</template>

<script>
	import starRating from '@/components/star-rating/star-rating.vue'
	import {
		getOrdersById
	} from '@/api/system/orders.js'
	import {
		addByUser
	} from '@/api/system/reviews.js'
	import {
		getToken
	} from '@/utils/auth'

	export default {
		components: {
			starRating
		},
		data() {
			return {
				dishNames: '',
				orderDetail: [],
				rating: 0, //0获取全部
				// descriptionRating: 0, 
				content: '', //内容
				imageList: [], // 存储图片路径（本地临时路径或服务器URL）
				serverUrls: [], // 存储服务器返回的图片URL（用于最终提交）
				isAnonymous: false, //匿名默认否0

			}
		},
		onLoad(options) {
			const id = options.orderId;
			console.log('接收到的 orderId:', id);
			this.getOrders(id)
		},
		computed: {
			dishNames() {
				return this.orderDetail.detailsList.map(item => item.dishName).join(', ')
			},

			canSubmit() {
				return this.rating > 0 && this.content.trim().length > 0
			}
		},
		methods: {
			getOrders(id) {
				getOrdersById(id).then(res => {
					console.log('order结果:', res.data);
					this.orderDetail = res.data
					let dishNames = '';
					for (let i = 0; i < this.orderDetail.detailsList.length; i++) {
						dishNames += this.orderDetail.detailsList[i].dishName;
						// 如果不是最后一个元素，添加分隔符（例如逗号）
						if (i < this.orderDetail.detailsList.length - 1) {
							dishNames += ', ';
						}
					}
					this.dishNames = dishNames
				})
			},
			//匿名选中
			anonymousChange(e) {
				this.isAnonymous = !!e.detail.value.length
				console.log('e.detail:', e.detail);
			},
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 5 - this.imageList.length, // 还能选择的图片数量
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 添加到图片列表（这里可以直接显示本地路径，上传成功后替换为服务器URL）
						this.imageList = [...this.imageList, ...res.tempFilePaths];
						console.log(this.imageList);
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},
			// 删除图片
			deleteImage(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					success: (res) => {
						if (res.confirm) {
							this.imageList.splice(index, 1);
							// 如果已经上传过，也需要从服务器URL数组中删除
							if (this.serverUrls[index]) {
								this.serverUrls.splice(index, 1);
							}
						}
					}
				});
			},
			// 上传图片方法
			async uploadImages() {
				const uploadTasks = this.imageList.map((image, index) => {
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: 'http://134.175.182.248/prod-api/common/upload', // 服务器接口地址
							filePath: image,
							name: 'file',
							header: {
								'Authorization': 'Bearer ' + getToken() // 如果需要认证
							},
							formData: {
								// 可以添加其他表单数据
								'type': 'review'

							},

							success: (res) => {
								if (res.statusCode === 200) {
									const data = JSON.parse(res.data)
									resolve("http://134.175.182.248/prod-api/" + data
										.fileName
									) // 假设返回数据格式为 { code: 200, data: { url: '图片URL' } }
									console.log('上传成功:', data);
								} else {
									reject(new Error('上传失败'))
								}
							},
							fail: (err) => {
								reject(err)
							}
						})
					})
				})

				return Promise.all(uploadTasks)
			},

			submitEvaluate() {
				if (!this.rating) {
					uni.showToast({
						title: '请评分',
						icon: 'none'
					})
					return
				}
				if (!this.content.trim()) {
					uni.showToast({
						title: '请输入评价内容',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '提交中...'
				})

				// 如果有图片，先上传图片
				if (this.imageList.length > 0) {
					this.uploadImages().then(urls => {
						console.log(urls);
						this.serverUrls = urls
						this.submitReview()
					}).catch(err => {
						uni.hideLoading()
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						})
					})
				} else {
					// 没有图片直接提交评价
					this.submitReview()
				}
			},

			// 提交评价方法
			submitReview() {
				// 将 serverUrls 转换为纯字符串数组（去除 Observer 相关属性）
				const imageUrls = this.serverUrls.filter(url => typeof url === 'string');

				// 用逗号分隔图片URL（如果后端需要字符串而不是数组）
				const imagesString = imageUrls.join(',');

				const reviews = {
					title: this.dishNames,
					orderId: this.orderDetail.id, // 添加订单ID
					productId: this.orderDetail.detailsList[0].dishId, // 修复拼写错误并确保取到正确的
					rating: this.rating,
					content: this.content,
					isAnonymous: this.isAnonymous ? 1 : 2, // 布尔值转 Integer（1或0）
					images: imagesString // 添加图片URL数组
				}

				// 这里可以处理上传成功后的逻辑
				console.log('title:', reviews.title);
				console.log('所有图片上传成功:', this.serverUrls[0]);
				console.log('orderId:', this.orderDetail.id);
				console.log('rating:', this.rating);
				console.log('content:', this.content);
				console.log('isAnonymous:', this.isAnonymous);
				console.log('图片URL数组:', imageUrls);
				console.log('逗号分隔的图片URL:', imagesString);

				addByUser(reviews).then(res => {
					uni.hideLoading()
					uni.showToast({
						title: '评价提交成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1500)
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: '评价提交失败',
						icon: 'none'
					})
				})
			}

		}
	}
</script>

<style scoped>
	.evaluate-container {
		padding: 30rpx;
		background-color: #f7f7f7;
		min-height: 100vh;
	}

	.product-info {
		display: flex;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.product-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
	}

	.product-detail {
		flex: 1;
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		lines: 2;
	}

	.product-price {
		font-size: 32rpx;
		color: #f40;
		font-weight: bold;
	}

	.section-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: bold;
	}

	.rating-section {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.evaluate-input {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.textarea {
		width: 100%;
		height: 200rpx;
		font-size: 28rpx;
	}

	.word-count {
		text-align: right;
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.upload-section {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.upload-list {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
	}

	.upload-item,
	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		position: relative;
	}

	.uploaded-image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
	}

	.delete-icon {
		position: absolute;
		right: 0;
		top: 0;
		background-color: rgba(0, 0, 0, 0.5);
		border-bottom-left-radius: 8rpx;
		padding: 4rpx;
	}

	.upload-btn {
		border: 1rpx dashed #ddd;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 8rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.upload-tip {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

/* 	.anonymous-section {
		padding: 30rpx;
		border-radius: 12rpx;
		margin-bottom: 40rpx;
	}

	.anonymous-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 10rpx;
	}

	.anonymous-checkbox {
		width: 50rpx;
		height: 50rpx;
		transform: scale(1);
		margin-right: 10rpx;
	}

	.anonymous-label {
		display: flex;
		align-items: center;
	} */
.custom-checkbox {
    display: flex;
    align-items: center;
}
 
.checkbox-box {
    width: 46rpx;
    height: 46rpx;
    border: 1px solid #ccc;
    border-radius: 4rpx;
    margin: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}
 
.checkbox-box.checked {
    background-color: #14ec04;
    border-color: #007AFF;
}
	.submit-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 45rpx;
		font-size: 32rpx;
		background-color: #007AFF;
	}

	.submit-btn[disabled] {
		background-color: #ccc;
		color: #fff;
	}
</style>